package com.sikaryofficial.backend.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.sikaryofficial.backend.domain.entity.Address;
import com.sikaryofficial.backend.domain.mapping.AddressMapping;
import com.sikaryofficial.backend.mapper.AddressMapper;
import com.sikaryofficial.backend.service.IAddressService;
import com.sikaryofficial.system.api.model.AddressDTO;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 地址Service业务层处理
 *
 * @author qinjinyuan
 * @date 2023-11-14
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {

    /**
     * 根据地址ID查询地址
     *
     * @param addressIds 地址ID集合
     * @return key=地址ID,value=地址对象
     */
    @Override
    public Map<Long, AddressDTO> getAddressByIds(List<Long> addressIds) {
        if (CollUtil.isEmpty(addressIds)) {
            return Maps.newHashMap();
        }
        List<Address> addresses = this.list(new LambdaQueryWrapper<Address>()
                .eq(Address::getDeletedVersion, 0L)
                .in(Address::getAddressId, addressIds)
        );

        if (CollUtil.isEmpty(addresses)) {
            return new HashMap<>(0);
        }
        List<AddressDTO> addressDTOS = AddressMapping.INSTANCE.coverListToResp(addresses);
        return addressDTOS.stream().collect(Collectors.toMap(AddressDTO::getAddressId, Function.identity(), (k1, k2) -> k1));
    }

    /**
     * 根据地址ID查询地址
     *
     * @param addressId 地址ID
     * @return 地址对象
     */
    @Override
    public AddressDTO getAddressById(Long addressId) {
        if (Objects.isNull(addressId)) {
            return null;
        }
        Address address = this.getOne(new LambdaQueryWrapper<Address>()
                .eq(Address::getDeletedVersion, 0L)
                .eq(Address::getAddressId, addressId)
                .last(" limit 1 ")
        );
        if (Objects.isNull(address)) {
            return null;
        }
        return AddressMapping.INSTANCE.coverToResp(address);
    }
}
